package cn.elead.chaos.framework.web.enums;

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

/**
 * <p>
 * 枚举工厂转换类
 * </p>
 * https://blog.csdn.net/goldenfish1919/article/details/90479599
 *
 * @author luopeng
 */
@SuppressWarnings("rawtypes")
public class IEnumConverterFactory implements ConverterFactory<String, IEnum> {

	
	@Override
	@SuppressWarnings("unchecked")
	public <T extends IEnum> Converter getConverter(Class<T> targetType) {
		return new StringToEnum<T>(targetType);
	}

	private static class StringToEnum<T extends IEnum> implements Converter<String, T> {
		private final Class<T> enumClass;

		public StringToEnum(Class<T> enumClass) {
			this.enumClass = enumClass;
		}

		@Override
		public T convert(String source) {
			if (source.length() == 0) {
				return null;
			}
			return EnumFactory.convertByStringValue(this.enumClass, source);
		}
	}
}
